package com.mmdccj.yugu.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author: star_
 * @date: 2023-11-28 19:01
 * 全局异常处理
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    /**
     * 处理SQL唯一索引约束的异常处理方法
     *
     * @param exception 异常
     * @return Result<String>
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> uniqueExceptionHandler(SQLIntegrityConstraintViolationException exception) {
        log.error(exception.getMessage());
        // 匹配 "idx_unique_music" 唯一索引
        if (exception.getMessage().contains("idx_unique_music")) {
            return Result.error("该音乐已添加");
        }

        return Result.error("未知错误");
    }
}
